function matchQueryString(query, name) {
  if (!query)
    return;
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = query.match(reg);
  return (r && r[2]) || '';
}

/** 是否支持本地缓存* */
function isLocalStorageNameSupported() {
  var testKey = 'test', storage = window.localStorage;
  try {
    storage.setItem(testKey, '1');
    storage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
}

function getJSONParsedObject(objectValue, message) {
  var rt;
  try {
    if(objectValue!=='')
       rt = JSON.parse(objectValue)
  } catch (err) {
    new UserPrompt(message);
    throw new Error(message);  
  }
  return rt;
}

/** 是否为移动端* */
function isMobileClient() {
  return navigator.userAgent.match(/(iphone|ipod|android|ios)/i);
}

function getCallerObject() {
  var caller = localCache.getSessionItem('caller');// 主叫号码
  var callerName = localCache.getSessionItem('callerName');// 主叫姓名
  return {
    data : [ {
      name : callerName,
      telephone : caller,
      type : 'main'
    } ]
  };
}

function getAllCalleesObject() {
  var contacts = localCache.getSessionItem('contacts');
  if (contacts)
    return JSON.parse(contacts);
  else
    return null;
}

function createMeeting(url, data) {
  if (!data) {
    data = getCallerObject();
  }
  location.assign(encodeURI(url + '?data=' + JSON.stringify(data)));
}

/**
 * 返回时间，格式为“201601280840”
 * 
 * @returns
 */
Date.prototype.getDateTime = function() {
  var rc = [];
  var year = this.getFullYear();
  rc.push(year);
  (function() {
    for (var i = 0; i < arguments.length; i++) {
      if (arguments[i] < 10) {
        rc.push(0);
      }
      rc.push(arguments[i]);
    }
  })(this.getMonth() + 1, this.getDate(), this.getHours(), this.getMinutes());
  return rc.join('');
}

function formatDateTime(value) {
  var rc = [];
  rc.push(value.substr(4, 2), '-');
  rc.push(value.substr(6, 2), ' ');
  rc.push(value.substr(8, 2), ':');
  rc.push(value.substr(10, 2));
  return rc.join('');
}

function formatDate(value) {
  var rc = [];
  rc.push(value.substr(4, 2), '-');
  rc.push(value.substr(6, 2));
  return rc.join('');
}

function validateNumber(number) {
  var checkResult = {
    success : true,
    msg : '号码校验通过'
  }; 
//  if (/[^0-9]/.test(number)) {// 存在非数字
//    checkResult.success = false;
//    checkResult.msg = '您输入的号码有误，请重新输入';
//    return checkResult;
//  }
  var l = number.length;
  if ((l === 7 || l === 8) && number.charAt(0) !== '0') {
    checkResult.success = false;
    checkResult.msg = '您输入的号码有误，若输入固话号码，请加区号';
  } else if (l !== 11 && l !== 12) {
    checkResult.success = false;
    checkResult.msg = '您输入的号码有误，请重新输入';
  }
  return checkResult;
}

function getHeight(context, elems) {
  var context = context || $(document);
  var height = context.height();
  if (elems) {
    for (var i = 0; i < elems.length; i++) {
      height -= elems[i].outerHeight(true);
    }
  }
  return height-20;
}

function Prompt(elems, context,closecallback) {
  this.context = context ? context : $(document.body);
  this.eles = [];
  this.closecallback=closecallback;
  if (elems) {
    for (var i = 0; i < elems.length; i++) {
      this.eles.push($('<div></div>').attr('id', elems[i].id));
      if (elems[i].html) {
        this.eles[i].html(elems[i].html);
      }
      if (elems[i].style) {
        this.eles[i].css(elems[i].style);
      }
      if (elems[i].handler && typeof elems[i].handler == 'function') {
        elems[i].handler.call(this.eles[i], this);
      }
      this.eles[i].appendTo(this.context);
    }
  }
}

Prompt.prototype.close = function() {
  var elems = this.eles;
  for (var i = elems.length - 1; i >= 0; i--) {
    elems[i].remove();
  }
  if(this.closecallback)
	  this.closecallback();
}

function LoadPrompt(text, context, customHandler) {
  Prompt.call(this, [ {
    id : 'mask',
    handler : customHandler || function() {
      var target = $(window);
      this.height(target.height());
      this.width(target.width());
    }
  }, {
    id : 'login'
  }, {
    id : 'info_text',
    html : text
  } ], context);
}

function NavigationPrompt(html) {
  Prompt.call(this, [ {
    id : 'mask_more',
    handler : function(prompt) {
      var target = $(window);
      this.height(target.height());
      this.width(target.width());
      this.on('click', function() {
        prompt.close.call(prompt);
      });
    }
  }, {
    id : 'more_alert',
    html : html,
    handler : function(prompt) {
      this.find('#account').on('click', function() {
        var isAdmin = localCache.getSessionItem('isAdmin');
        if (isAdmin) {// 管理员
          location.assign('account_recharge.html');
        } else
          location.assign('account.html');
      });
      this.find('#help').on('click', function() {
         location.assign('help.html');
      });
    },
    style : {
      top : '43px'
    }
  } ]);
}

function UserPrompt(html,func) {
  Prompt.call(this, [{
    id : 'mask_more',
    handler : function(prompt) {
      var target = $(window);
      this.height(target.height());
      this.width(target.width());
    }
  }, {
    id : 'make_sure',
    html : '<p>' + html + '</p><div class="input_ok" id="confirm">确定</div>',
    handler : function(prompt) {
      $(document).on('click', '#confirm', function() {
        prompt.close.call(prompt);
      });
    }
  }],null,func);
}

function ConfirmPrompt(text,func) {
	var $this=this;
    Prompt.call(this, [{
    	handler:function() {
    	      var target = $(window);
    	      this.height(target.height());
    	      this.width(target.width());
    	 },
    	 id:'mask'
        },{
    	id:'alert_tip',
		html:'<p>'+text+'</p><div class="btn" ><span class="bordeR" id="save">确定</span><span id="cancel">取消</span></div>',
	    handler : function(prompt) {
	        $(document).on('click', '#cancel', function() {
	            prompt.close();
	        });
	        $(document).on('click', '#save', function() {
	        	func.save(prompt);
		    });
	      }
    }]);
}

function handlerError(evtName, callback, data) {
  window.addEventListener(evtName, callback);
  var evt = document.createEvent("Event");
  evt.initEvent(evtName, false, false);
  if (data)
    evt.data = data;
  window.dispatchEvent(evt);
}

$(function() {
  UserPrompt.prototype = NavigationPrompt.prototype = LoadPrompt.prototype =ConfirmPrompt.prototype=new Prompt();
  $('#more').on('click', function(e) {
    e.stopPropagation();
    var html = '<div id="more_alert_content"><a id="help"><dt><img src="images/help.png" width="60" height="60"></dt>';
    html += '<dd>帮助</dd></a><a id="account"><dt><img src="images/accout.png" width="60" height="60"></dt>';
    html += '<dd>账户</dd></a></div><i class="arrow_up"></i>';
    new NavigationPrompt(html);
  });
  var userId=localCache.getSessionItem('userId');
  if(userId===null||userId===''||userId==='undefined'){
	  var search=decodeURI(window.location.search.substr(1)),
	  userId=matchQueryString(search,'ext_terminalCode');
	  if(userId===''){
		  var callerInfo=matchQueryString(search,'caller');
		  var object=getJSONParsedObject(callerInfo,'主叫信息参数格式错误');
		  userId=(object&&object.telephone)||'';   	      
	  }
  }
  /**
   * 通话记录缓存
   */
  window.meetCache = {
    maxSize : 50,
    key : 'ms'+userId,
    userId :userId,
    storageMeet : function(data) {
      var local = localCache.getItemIdentify(meetCache.key);
      if (local) {
        local = JSON.parse(local);
        if (local.length >= meetCache.maxSize) {
          local.pop();
        }
        localCache.cacheItemIdentify(meetCache.key, JSON.stringify([ data ].concat(local)));
      } else {
        localCache.cacheItemIdentify(meetCache.key, JSON.stringify([ data ]));
      }
    },
    getMeetStorage : function() {
      var local = localCache.getItemIdentify(meetCache.key);
      return local ? JSON.parse(local) : [];
    },
    hasMeetStorage : function() {
      var local = localCache.getItemIdentify(meetCache.key);
      return local ? true : false;
    },
    setMeetStatus : function(sessionId, status) {// success 成功 fail 失败
      var meets = meetCache.getMeetStorage();
      if (meets.length > 0) {
        for (var m = 0; m < meets.length; m++) {
          var meet = meets[m];
          if (meet.session_id == sessionId) {
            meet.status = status;
            localCache.cacheItemIdentify(meetCache.key, JSON.stringify(meets));
            return true;
          }
        }
      }
      return false;
    },
    addMeetMembers : function(sessionId, members) {
      var meets = meetCache.getMeetStorage();
      if (meets.length > 0) {
        for (var m = 0; m < meets.length; m++) {
          var meet = meets[m];
          if (meet.session_id == sessionId) {
            Array.prototype.push.apply(meet.data, members);
            localCache.cacheItemIdentify(meetCache.key, JSON.stringify(meets));
            return true;
          }
        }
      }
      return false;
    },
    updateMeetInfo:function(sessionId,newMeet){//更新数据
        var meets = meetCache.getMeetStorage();
        if (meets.length > 0) {
          for (var m = 0; m < meets.length; m++) {
            var meet = meets[m];
            if (meet.session_id == sessionId) {
              $.extend(meet.sessionArray,newMeet);
              localCache.cacheItemIdentify(meetCache.key, JSON.stringify(meets));
              return true;
            }
          }
        }  
        return false;
    }    
  }

  window.platFormUtils = {
    getAskCode : function(param, callback) {
      $.ajax({
        type : "post",
        url : localCache.getSessionItem('getcode_url'),
        dataType : "json",
        async : true,
        data : param,
        success : function(rc) {
          if (rc.flag === '0000') {
            if (callback)
              callback(rc.ask_code);
          }
        }
      });
    }
  };
  
  window.utils={
    lazyload:function(func){
   	  var range = 50,totalheight = 0;   
	  $(window).scroll(function(){
	      var srollPos = $(window).scrollTop();//滚动条距顶部距离(页面超出窗口的高度)
	      totalheight = parseFloat($(window).height()) + parseFloat(srollPos);
	      if(($(document).height()-range) <= totalheight&&func&&typeof func==='function') {
	    	 func();
	      }
	   });
     }
   }

});
